<template>
  <nav class="app-topnav">
    <div class="container">
      <ul>
        <!--
          登录状态适配一下UI显示
          template + v-if
         -->
        <!-- 登录时 -->
        <template v-if="token">
          <li>
            <a href="javascript:;"
              ><i class="iconfont icon-user"></i>{{ nickname }}</a
            >
          </li>
          <li><a href="javascript:;" @click="loginOut">退出登录</a></li>
        </template>
        <!-- 未登录时 -->
        <template v-else>
          <li><a href="javascript:;" @click="goLogin">请先登录</a></li>
          <li><a href="javascript:;" @click="goLogin(1)">免费注册</a></li>
        </template>
        <li><a href="javascript:;" @click="userCenter">会员中心</a></li>
        <li><a href="javascript:;">帮助中心</a></li>
        <li><a href="javascript:;">关于我们</a></li>
      </ul>
    </div>
  </nav>
</template>
<script>
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import Message from '@/components/Message/index.js'
export default {
  name: 'top-nav',
  setup () {
    const user = computed(() => store.state.user.profile)
    const router = useRouter()
    function goLogin (a) {
      // this.$router.push()
      router.push(`/login/${a}`)
    }

    // 如何在setup中使用vuex中的数据
    // 计算属性进行映射
    // mapState mapGetters 数据  ->  computed
    // mapMutations mapActions  方法 -> methods
    const store = useStore()
    const route = useRoute()
    // 退出登录
    function loginOut () {
      // 1. 清空数据
      // 2. 跳回到首页 (携带参数)
      store.commit('user/clearUserInfo')
      router.push({
        path: '/login/2',
        query: {
          redirect: encodeURIComponent(route.fullPath)
        }
      })
    }
    const nickname = computed(() => store.state.user.profile.nickname)
    // 跳转到个人中心
    function userCenter () {
      if (user.value.id) {
        console.log(user.value)
      } else {
        Message({ text: '请先登录', type: 'warn' })
        router.push('/login/2')
        return
      }
      router.push(`/user/${nickname.value}`)
    }
    return {
      goLogin,
      token: computed(() => store.state.user.profile.token),
      nickname,
      loginOut,
      userCenter
    }
  }
}
</script>
<style scoped lang="less">
.app-topnav {
  background: #333;
  ul {
    display: flex;
    height: 53px;
    justify-content: flex-end;
    align-items: center;
    li {
      a {
        padding: 0 15px;
        color: #cdcdcd;
        line-height: 1;
        display: inline-block;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
        &:hover {
          color: @xtxColor;
        }
      }
      ~ li {
        a {
          border-left: 2px solid #666;
        }
      }
    }
  }
}
</style>
